<!--表格操作列组件，例如详情，删除按钮,超出最大个数按钮改下拉-->
<template>
  <div class="root-box">
    <div ref="slotArea" v-show="moreNodes.length==0" class="slot-box">
      <slot></slot>
    </div>
    <div v-show="moreNodes.length>0">
      <custom-panel :vnodes="showNodes"></custom-panel>
      <a-dropdown :trigger="['click']">
        <a @click.stop>更多<a-icon type="down" /></a>
        <a-menu slot="overlay">
          <a-menu-item v-for="(item,index) of moreNodes" :key="index">
            <custom-panel :vnodes="[item]"></custom-panel>
          </a-menu-item>
        </a-menu>
      </a-dropdown>
    </div>
  </div>
</template>

<script>
  export default {
    name: 'AntTableButtonGroup',
    components: {
      'custom-panel': {
        functional: true,
        render(h, ctx) {
          return h('span', {
            attrs: { 'moreflag': '1', 'class': 'more-content' },
            style: {}
          }, ctx.props.vnodes)
        }
      }
    },
    props: {
      /**
       * 最大按钮个数
       */
      max: {
        required: false,
        type: Number,
        default: 3
      }
    },
    data() {
      return {
        showNodes: [],
        moreNodes: []
      }
    },
    created() {
      this.updateLayout()
    },
    mounted() {
      const that = this
      // 设置observer的配置选项
      const config = { attributes: true, childList: true, subtree: true }
      // 创建一个observer示例与回调函数相关联,更新插槽视图
      const observer = new MutationObserver((mutationsList, observer) => {
        that.updateLayout()
      })
      observer.observe(this.$refs.slotArea, config)
    },
    methods: {
      updateLayout() {
        let slots = this.$slots.default
        // 去掉tag为undefined的item（调用处可能使用v-if来判断来控制某item）
        slots = slots.filter(item => item.tag)
        if (slots.length > this.max) {
          this.showNodes = slots.slice(0, this.max - 1)
          this.moreNodes = slots.slice(this.max - 1)
        } else {
          this.moreNodes = []
        }
      },
    },
  }
</script>

<style scoped="c-table-tool">
  .slot-box > *:not(:first-child){
    margin-left: 10px;
  }
  .more-content > *{
    margin-right: 10px!important;
  }
  .ant-dropdown-menu-item, .ant-dropdown-menu-submenu-title {
    cursor: default;
  }
</style>
